const http = require("../../../utils/http");

Page({
  data: {
    userNumber: '', // 当前登录用户的学号/工号
    classroomInfo: null, // 如果有教室信息
  },

  onLoad() {
    // 假设你已在登录时缓存了 userNumber
    const userNumber = wx.getStorageSync('userInfo').userNumber || '';
    console.log(userNumber);
    this.setData({ userNumber }, () => {
      this.loadClassroomInfo();
    });
  },

  loadClassroomInfo() {
    http('/classroom/myApplications', {
      userNumber: this.data.userNumber
    }, 'POST', {}).then(res => {
      if (res.data.success && res.data.data) {
        const classroomInfo = res.data.data;
        // 判断日期并修改
        const currentDate = new Date();
        const isNextDay = classroomInfo.date === '次日';
        const date = isNextDay ? new Date(currentDate.setDate(currentDate.getDate() + 1)) : currentDate;
  
        // 格式化日期为 YYYY-MM-DD
        const formattedDate = date.toISOString().split('T')[0];
  
        // 设置 classroomInfo
        this.setData({
          classroomInfo: {
            ...classroomInfo,
            date: formattedDate,
            time: classroomInfo.time, // 时间段不变
            applicantName: wx.getStorageSync('userInfo').userName // 获取申请人名称
          }
        });
      } else {
        this.setData({
          classroomInfo: null
        });
      }
      wx.setStorageSync('classroomInfo', this.data.classroomInfo);
    });
  },

  Borrow() {
    wx.navigateTo({
      url: '/pages/User/Borrow/Borrow'
    });
  },
  Fetch() {
    wx.navigateTo({
      url: '/pages/User/Fetch/Fetch'
    });
  },
  Back() {
    wx.navigateTo({
      url: '/pages/User/Back/Back'
    });
  },
  showReminderDialog() {
    const info = this.data.classroomInfo;
    if (!info) return;
  
    const content = `教室：${info.classroomNumber}\n日期：${info.date}\n时间：${info.time}\n申请人：${info.applicantName}`;
  
    wx.showActionSheet({
      itemList: ['提前10分钟提醒', '提前30分钟提醒', '提前1小时提醒'],
      success: (res) => {
        const selected = res.tapIndex;
        let minutesBefore = 10;
        if (selected === 1) minutesBefore = 20;
        if (selected === 2) minutesBefore = 30;
  
        // 设置本地提醒或发请求设置推送提醒
        this.scheduleReminder(info, minutesBefore);
      }
    });
  },
  scheduleReminder(info, minutesBefore) {
    const timeStr = info.time.split('、')[0].split('-')[0]; // 比如 "16:15"
    const [hour, minute] = timeStr.split(':').map(Number);
    const targetDate = new Date(info.date);
    targetDate.setHours(hour);
    targetDate.setMinutes(minute - minutesBefore);
    targetDate.setSeconds(0);
  
    const reminderTime = targetDate.getTime();
    console.log("reminder: " + reminderTime);
    // 存储提醒信息
    wx.setStorageSync('reminderInfo', {
      classroomNumber: info.classroomNumber,
      time: info.time,
      applicantName: info.applicantName,
      reminderTime
    });
  
    wx.showModal({
      title: '提醒设置成功',
      content: `将在使用前${minutesBefore}分钟提醒您。`,
      showCancel: false
    });
  }
});